/*
 PureMVC AS3 Demo - Flex CafeTownsend
 Copyright (c) 2007-08 Michael Ramirez <michael.ramirez@puremvc.org>
 Parts Copyright (c) 2005-07 Adobe Systems, Inc. 
 Your reuse is governed by the Creative Commons Attribution 3.0 License
 */
package vn.demand.dragon.view
{
	import flash.events.Event;
	import flash.net.FileReference;
	import flash.net.URLRequest;
	import flash.net.navigateToURL;
	
	import flexed.widgets.alerts.alert;
	
	import mx.collections.XMLListCollection;
	import mx.controls.Alert;
	import mx.controls.advancedDataGridClasses.AdvancedDataGridColumn;
	import mx.events.CloseEvent;
	import mx.managers.PopUpManager;
	
	import org.puremvc.as3.interfaces.*;
	import org.puremvc.as3.patterns.mediator.Mediator;
	
	import vn.demand.dragon.CommonCommand;
	import vn.demand.dragon.FFIAApplicationFacade;
	import vn.demand.dragon.model.MasterdataProxy;
	import vn.demand.dragon.model.ReferenceProxy;
	import vn.demand.dragon.view.components.ArchivedProjectResult;
	import vn.demand.dragon.view.components.PrintDebitDialog;
	import vn.demand.dragon.view.components.ReferenceAccountingList;
	import vn.demand.utils.DpUtils;
    
    /**
     * A Mediator for interacting with the EmployeeList component
     */
    public class ReferenceAccountingListMediator extends Mediator implements IMediator
    {
        // Cannonical name of the Mediator
        public static const NAME:String = "ReferenceAccountingListMediator";
        
        var dialog:PrintDebitDialog = null;
        
        public var searchData:Object;
        
        public var fRef:FileReference = new FileReference();
        /**
         * Constructor. 
         */
        public function ReferenceAccountingListMediator( viewComponent:Object ) 
        {
            // pass the viewComponent to the superclass where 
            // it will be stored in the inherited viewComponent property
            super( NAME, viewComponent );
			
			referenceProxy = ReferenceProxy( facade.retrieveProxy( ReferenceProxy.NAME ) );
			masterdataProxy = MasterdataProxy( facade.retrieveProxy( MasterdataProxy.NAME ) );
			
			projectList.addEventListener(ReferenceAccountingList.SELECT_REFERENCE, onSelectReference);
			projectList.addEventListener(ReferenceAccountingList.REFRESH_REFERENCE, onRefreshReference);
			projectList.addEventListener(ReferenceAccountingList.CLOSE_REFERENCE_LIST, closeReferenceAccountingList);
			projectList.addEventListener('printDebit', onPrintDebit);
			projectList.addEventListener('debitDetails', onPrintDebitDetails);
			projectList.addEventListener('finishProject', onFinishProjects);
			projectList.addEventListener('openProject', onOpenProject);
			projectList.addEventListener('openTasks', onOpenTasks);
			projectList.addEventListener('openTaskLogs', onOpenTaskLogs);
			
			projectList.dgQuotation.groupedColumns[4].labelFunction = lfProjectStatus;
        }
        
        public function onOpenProject(event:Event):void {
        	if (projectList.dgQuotation.selectedItem == null) {
        		alert.error('Please select a row');
        		return;
        	}
			sendNotification(CommonCommand.REFERENCE_SELECTED, projectList.dgQuotation.selectedItem);
        }
        
        public function onOpenTasks(event:Event):void {
			sendNotification(CommonCommand.OPEN_PROJECT_TASKS_PANEL, projectList.dgQuotation.selectedItem);
		}
		
		public function onOpenTaskLogs(event:Event):void {
			sendNotification(CommonCommand.OPEN_PROJECT_TASK_LOGS_PANEL, projectList.dgQuotation.selectedItem);
		}
        
		public function onSelectReference(event:Event):void {
			if (projectList.dgQuotation.selectedIndex < 0) {
				alert.error("You should select a reference");
				return;
			}
			sendNotification(CommonCommand.REFERENCE_SELECTED, projectList.dgQuotation.selectedItem);
		}
		
		public function doPrintDebit(event:Event):void {
			var project_company:String = 'project_company=' + searchData.project_company;
			var debit_invoice:String = 'debit_invoice='+ dialog.invoiceNo.text;
			var debit_note:String = 'debit_note=' + dialog.note.text;
			var fromDate:String = 'complete_from_date=' + dialog.fromDate.date2String;
			var toDate:String = 'complete_to_date=' + dialog.toDate.date2String;
			var project_currency:String = 'project_currency=5';
			var exchange_rate:String = '6_vnd=' + projectList.exchangeRate.text.replace(',', '');
			var url:String = "http://dev.dragon.com/index.php?m=projects&a=do_print_debit_note&suppressHeaders=1" +
				"&" + project_company + 
				"&" + fromDate + 
				"&" + toDate + 
				"&" + debit_invoice + 
				"&" + debit_note + 
				"&" + exchange_rate;
			var urlRequest:URLRequest = new URLRequest(url);
			navigateToURL(urlRequest, '_blank');
			PopUpManager.removePopUp(dialog);
		}
		
		public function onPrintDebit(event:Event):void {
			if (searchData == null || Number(searchData.project_company) == NaN || Number(searchData.project_company) == 0) {
				alert.error('Please select customer on search form before doing print debit');  
				return;
			} 
			dialog = PopUpManager.createPopUp(projectList, PrintDebitDialog, true) as PrintDebitDialog;
			dialog.addEventListener('print', doPrintDebit);
			dialog.company.text = masterdataProxy.getCustomerById(Number(searchData.project_company));
			dialog.fromDate.selectedDate = DpUtils.parseDate(searchData.complete_from_date);
			dialog.toDate.selectedDate = DpUtils.parseDate(searchData.complete_to_date);
			PopUpManager.centerPopUp(dialog);
		}
		
		public function onPrintDebitDetails(event:Event):void {
			if (searchData == null || Number(searchData.project_company) == NaN || Number(searchData.project_company) == 0) {
				alert.error('Please select customer on search form before open debit details');  
				return;
			}
			dialog = PopUpManager.createPopUp(projectList, PrintDebitDialog, true) as PrintDebitDialog;
			dialog.addEventListener('print', doPrintDebitDetails);
			dialog.company.text = masterdataProxy.getCustomerById(Number(searchData.project_company));
			dialog.fromDate.selectedDate = DpUtils.parseDate(searchData.complete_from_date);
			dialog.toDate.selectedDate = DpUtils.parseDate(searchData.complete_to_date);
			PopUpManager.centerPopUp(dialog); 
		}
		
		public function doPrintDebitDetails(event:Event):void {
			var project_company:String = 'project_company=' + searchData.project_company;
			var fromDate:String = 'complete_from_date=' + dialog.fromDate.date2String;
			var toDate:String = 'complete_to_date=' + dialog.toDate.date2String;
			var debit_invoice:String = 'debit_invoice='+ dialog.invoiceNo.text;
			var project_currency:String = 'project_currency=5';
			var exchange_rate:String = '6_vnd=' + projectList.exchangeRate.text.replace(',', '');
			var url:String = "http://dev.dragon.com/index.php?m=projects&a=do_debit_details&suppressHeaders=1" +
				"&" + project_company + 
				"&" + fromDate + 
				"&" + toDate + 
				"&" + debit_invoice + 
				"&" + exchange_rate;
			var urlRequest:URLRequest = new URLRequest(url);
			navigateToURL(urlRequest);
//			fRef.download(urlRequest, masterdataProxy.getCustomerById(Number(searchData.project_company)) 
//								+ '_debit_details_' 
//								+ DpUtils.dateFormatter.format(new Date()) 
//								+ '.xls');
		} 
		
		public function onFinishProjects(event:Event):void {
			var dp:Object = projectList.dgQuotation.dataProvider;
			var s:String = "";
			var i:int = 0;
			var confirmText = "";
			for each(var item:Object in dp) {
				if (DpUtils.isTrue(item.project_color_identifier)) {
					s += (i == 0 ? '' : ',') + item.project_id;
					confirmText += (i == 0 ? '' : ',') + item.project_iso_code;
					i++
				}
			}
			alert.confirm("Do you want to finish these references: " + confirmText, function(event:CloseEvent) {
				if (event.detail == Alert.YES) {
					doFinish(s);
				}
			});
		}
		
		public function doFinish(params):void {			
			referenceProxy.archivedProjects(params);	
		}

		public function onRefreshReference(event:Event):void {
			sendNotification(FFIAApplicationFacade.REFRESH_REFERENCE, projectList.dgQuotation.selectedItem);
		}
		
		public function closeReferenceAccountingList(event:Event):void {
			sendNotification(FFIAApplicationFacade.CLOSE_REFERENCES_LIST, projectList);
		}
		
		public function onNewReference(event:Event):void {
			sendNotification(FFIAApplicationFacade.NEW_REFERENCE);
		}
	
		
		public function onDeleteReference(event:Event):void {
//			var sel: = new Supplier(supplierList.dgSupplier.selectedItem);
			alert.confirm("Do you want to remove?", function(e:CloseEvent) {
    		if (e.detail == Alert.NO) {
        			return;
        		}
				sendNotification(FFIAApplicationFacade.DELETE_REFERENCE, projectList.dgQuotation.selectedIndex);
        	});
		}
		
        /**
         * List all notifications this Mediator is interested in.
         * <P>
         * Automatically called by the framework when the mediator
         * is registered with the view.</P>
         * 
         * @return Array the list of Nofitication names
         */
        override public function listNotificationInterests():Array 
        {
            return [
            		CommonCommand.CLOSE_TAB, 
            		FFIAApplicationFacade.LOAD_REFERENCE_SUCCESS,            
					FFIAApplicationFacade.LOAD_REFERENCE_FAILED,
					FFIAApplicationFacade.LOAD_MASTERDATA_SUCCESS,
					FFIAApplicationFacade.REFRESH_REFERENCE,
					FFIAApplicationFacade.PROJECT_UPDATED,
					CommonCommand.DELETE_REFERENCE_SUCESSFUL,
					CommonCommand.DELETE_REFERENCE_FAILED,
					CommonCommand.ON_SEARCH_REFERENCES,
					CommonCommand.PROJECTS_ARCHIVED,
					CommonCommand.PROJECTS_ARCHIVE_FAILED
			];
        }

        /**
         * Handle all notifications this Mediator is interested in.
         * <P>
         * Called by the framework when a notification is sent that
         * this mediator expressed an interest in when registered
         * (see <code>listNotificationInterests</code>.</P>
         * 
         * @param INotification a notification 
         */
        override public function handleNotification( note:INotification ):void 
        {
            switch ( note.getName() ) 
			{
				case CommonCommand.CLOSE_TAB:
					if (note.getBody() == projectList) {
						sendNotification(FFIAApplicationFacade.CLOSE_REFERENCES_LIST);
					}
					break;
                case FFIAApplicationFacade.LOAD_REFERENCE_SUCCESS:
                    projectList.dgQuotation.dataProvider = referenceProxy.projectsListDP;
                    break;
				case FFIAApplicationFacade.LOAD_REFERENCE_FAILED:
					projectList.dgQuotation.errorString = referenceProxy.errorStatus;
					break;
				case FFIAApplicationFacade.REFRESH_REFERENCE:
					referenceProxy.loadReferences();
					break;
				case FFIAApplicationFacade.LOAD_MASTERDATA_SUCCESS:
					referenceProxy.loadReferences();
					break;
				case CommonCommand.ON_SEARCH_REFERENCES:
					searchData = note.getBody();
					break;
				case CommonCommand.PROJECTS_ARCHIVED:
					var popup:ArchivedProjectResult = PopUpManager.createPopUp(projectList, ArchivedProjectResult, true) as ArchivedProjectResult;
					popup.results.dataProvider = note.getBody() as XMLListCollection;
					PopUpManager.centerPopUp(popup);
					referenceProxy.loadReferences();
					break;
				case CommonCommand.PROJECTS_ARCHIVE_FAILED:
					alert.error(note.getBody() as String);
					break;
            }
        }
                    
        /**
         * Cast the viewComponent to its actual type.
         * 
         * <P>
         * This is a useful idiom for mediators. The
         * PureMVC Mediator class defines a viewComponent
         * property of type Object. </P>
         * 
         * <P>
         * Here, we cast the generic viewComponent to 
         * its actual type in a protected mode. This 
         * retains encapsulation, while allowing the instance
         * (and subclassed instance) access to a 
         * strongly typed reference with a meaningful
         * name.</P>
         * 
         * @return EmployeeList the viewComponent cast to EmployeeList
         */
        protected function get projectList():ReferenceAccountingList
		{
            return viewComponent as ReferenceAccountingList;
        }
		
        public function lfProjectStatus(item:Object, column:AdvancedDataGridColumn):String {
        	return masterdataProxy.getProjectStatusById(item[column.dataField]);
        }
		
		private var referenceProxy:ReferenceProxy;
		private var masterdataProxy:MasterdataProxy;
    }
}